<template>
    <div class="building-tree-access-door">
        <building-org-tree
            :loading="loading"
            :data="data"
            :menu-list="buildingTreeMenuList"
            @onPopoverShow="onBuildingTreePopoverShow"
            @onMenuClick="onBuildingTreeMenuClick"
        >
        </building-org-tree>

        <el-dialog
            v-model="buildingDialogShow"
            width="300px"
            :title="currentOperateMenuItem.name"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form ref="buildingFormRef" :model="buildingForm" :rules="buildingFormRules" label-position="top" inline>
                <el-form-item label="楼栋名称" prop="name">
                    <el-input v-model="buildingForm.name" placeholder="请输入" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="switchBuildingDialog">取消</el-button>
                    <el-button
                        type="primary"
                        :loading="dialogBtnLoading"
                        @click="currentOperateMenuItem.command === 'addBuilding' ? addBuilding() : updateBuildingName()"
                    >
                        <span>确认</span>
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog
            v-model="gateDialogShow"
            width="300px"
            :title="currentOperateMenuItem.name"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form ref="gateFormRef" :model="gateForm" :rules="gateFormRules" label-position="top" inline>
                <el-form-item label="出入门名称" prop="name">
                    <el-input v-model="gateForm.name" placeholder="请输入" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="switchGateDialog">取消</el-button>
                    <el-button
                        type="primary"
                        :loading="dialogBtnLoading"
                        @click="currentOperateMenuItem.command === 'addGate' ? addGate() : updateGateName()"
                    >
                        <span>确认</span>
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog
            v-model="gatewayDialogShow"
            width="300px"
            :title="currentOperateMenuItem.name"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form ref="gatewayFormRef" :model="gatewayForm" :rules="gatewayFormRules" label-position="top" inline>
                <el-form-item :label="+buildingTreeCurrentNodeData.gateType === 5 ? '门禁名称' : '道闸名称'" prop="name">
                    <el-input v-model="gatewayForm.name" placeholder="请输入" />
                </el-form-item>
                <el-form-item :label="+buildingTreeCurrentNodeData.gateType === 5 ? '门禁类型' : '道闸类型'" prop="subType">
                    <el-select v-model="gatewayForm.subType" placeholder="请选择">
                        <el-option
                            v-for="(elevatorType, index) in +buildingTreeCurrentNodeData.gateType === 5 ? accessControlList : roadGateList"
                            :key="index"
                            :label="elevatorType.name"
                            :value="elevatorType.code"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="switchGatewayDialog">取消</el-button>
                    <el-button
                        type="primary"
                        :loading="dialogBtnLoading"
                        @click="['addRoadGate', 'addAccessControl'].includes(currentOperateMenuItem.command) ? addGateway() : updateGateway()"
                    >
                        <span>确认</span>
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <point-drawer
            point-type="door"
            v-model:is-point-drawer-show="pointDrawerShow"
            :id="buildingTreeCurrentNodeData.id"
            :sign-type="buildingTreeCurrentNodeData.gateType"
            @onAddPointConfirm="emit('onDataChange')"
        >
        </point-drawer>
        <edit-point-drawer
            v-model:is-edit-point-drawer-show="editPointDrawerShow"
            :sign-type="buildingTreeCurrentNodeData.signType"
            :id="buildingTreeCurrentNodeData.id"
            @onEditPointConfirm="emit('onDataChange')"
        >
        </edit-point-drawer>
    </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ComponentInternalInstance, getCurrentInstance } from 'vue';
import { useStore } from 'vuex';
import BuildingOrgTree from '@/components/buildingOrgTree/Index.vue';
import PointDrawer from '@/views/resource/houseManage/components/Point.vue';
import EditPointDrawer from '@/views/resource/houseManage/components/EditPoint.vue';
import resourceApi from '@/api/resource';
import {
    BuildingTreeAccessDoorState,
    BuildingTreeData,
    BuildingTreeMenuItem,
} from './buildingTreeType';

const props = defineProps({
    loading: {
        type: Boolean,
        default: false
    },
    data: {
        type: Object,
        default: () => {
            return {};
        }
    },
});
const emit = defineEmits(['onDataChange']);

const store = useStore();
const roadGateList = store.state.app.common.CommonList.barrierList;
const accessControlList = store.state.app.common.CommonList.gaiingList;
const currentInstance = <ComponentInternalInstance>getCurrentInstance();
const state = reactive<BuildingTreeAccessDoorState>({
    buildingTreeData: {
        id: '',
        pid: '',
        level: 1,
        name: '',
        premisesId: '',
        signType: 5,
        buildId: '',
        eleType: '',
        gateType: '',
        subType: '',
        showEdit: false,
        showDelete: false,
        sonList: [],
        expand: true,
    },
    buildingTreeMenuList: [],
    buildingTreePopoverShow: false,
    buildingTreeCurrentNodeData: {
        id: '',
        pid: '',
        level: 1,
        name: '',
        premisesId: '',
        buildId: '',
        signType: 5,
        eleType: '',
        gateType: '',
        subType: '',
        showEdit: false,
        showDelete: false,
        sonList: [],
        expand: true,
    },
    currentOperateMenuItem: {
        command: '',
        name: '',
        show: true,
    },
    dialogBtnLoading: false,
    buildingDialogShow: false,
    buildingForm: {
        name: '',
    },
    buildingFormRules: {
        name: [
            { required: true, message: '请输入楼盘名称', trigger: 'blur' },
        ],
    },
    gateDialogShow: false,
    gateForm: {
        name: '',
    },
    gateFormRules: {
        name: [
            { required: true, message: '请输入出入门名称', trigger: 'blur' },
        ],
    },
    gatewayDialogShow: false,
    gatewayForm: {
        name: '',
        subType: '',
    },
    gatewayFormRules: {
        name: [
            { required: true, message: '请输入道闸名称', trigger: 'blur' },
        ],
        subType: [
            { required: true, message: '请选择道闸类型', trigger: 'change' },
        ],
    },
    pointDrawerShow: false,
    editPointDrawerShow: false,
});
const { 
    buildingTreeData,
    buildingTreeMenuList,
    buildingTreePopoverShow,
    buildingTreeCurrentNodeData,
    currentOperateMenuItem,
    dialogBtnLoading,
    buildingDialogShow,
    buildingForm,
    buildingFormRules,
    gateDialogShow,
    gateForm,
    gateFormRules,
    gatewayDialogShow,
    gatewayForm,
    gatewayFormRules,
    pointDrawerShow,
    editPointDrawerShow,
} = toRefs(state);

const onBuildingTreePopoverShow = (currentNodeData:BuildingTreeData) => {
    state.buildingTreeCurrentNodeData = currentNodeData;
    setBuildingTreeMenu();
};
const setBuildingTreeMenu = () => {
    if (state.buildingTreeCurrentNodeData.level === 1) {
        state.buildingTreeMenuList = [
            {
                command: 'addGate',
                name: '新建出入门',
                show: true,
            },
        ];
    }
    if (state.buildingTreeCurrentNodeData.level === 2) {
        state.buildingTreeMenuList = [
            {
                command: 'editGate',
                name: '编辑出入门',
                show: state.buildingTreeCurrentNodeData.showEdit,
            },
            {
                command: 'addRoadGate',
                name: '新建道闸',
                show: true,
            },
            {
                command: 'addAccessControl',
                name: '新建门禁',
                show: true,
            },
            {
                command: 'deleteGate',
                name: '删除',
                show: state.buildingTreeCurrentNodeData.showDelete,
            },
        ];
    }
    if (state.buildingTreeCurrentNodeData.level === 3) {
        state.buildingTreeMenuList = [
            // gateType-门体类型：5.门禁，6.道闸
            {
                command: 'editRoadGate',
                name: '编辑道闸',
                show: +state.buildingTreeCurrentNodeData.gateType === 6 && state.buildingTreeCurrentNodeData.showEdit,
            },
            {
                command: 'editAccessControl',
                name: '编辑门禁',
                show: +state.buildingTreeCurrentNodeData.gateType === 5 && state.buildingTreeCurrentNodeData.showEdit,
            },
            {
                command: 'managePoint',
                name: '管理点位',
                show: true,
            },
            {
                command: 'deleteGateway',
                name: '删除',
                show: state.buildingTreeCurrentNodeData.showDelete,
            },
        ];
    }
    if (state.buildingTreeCurrentNodeData.level === 4) {
        state.buildingTreeMenuList = [
            {
                command: 'editPoint',
                name: '编辑点位',
                show: true,
            },
        ];
    }
};
const onBuildingTreeMenuClick = (menuItem:BuildingTreeMenuItem) => {
    state.currentOperateMenuItem = menuItem;
    switch (menuItem.command) {
        // 新建楼栋
        case 'addBuilding':
            switchBuildingDialog();
            break;
        // 编辑楼栋
        case 'editBuilding':
            state.buildingForm.name = state.buildingTreeCurrentNodeData.name;
            switchBuildingDialog();
            break;
        // 删除楼栋
        case 'deleteBuilding':
            deleteBuilding();
            break;
        // 新建出入门
        case 'addGate':
            switchGateDialog();
            break;
        // 编辑出入门
        case 'editGate':
            state.gateForm.name = state.buildingTreeCurrentNodeData.name;
            switchGateDialog();
            break;
        // 删除出入门
        case 'deleteGate':
            deleteGate();
            break;
        // 新建道闸/门禁
        case 'addRoadGate':
            state.buildingTreeCurrentNodeData.gateType = '6';
            switchGatewayDialog();
            break;
        case 'addAccessControl':
            state.buildingTreeCurrentNodeData.gateType = '5';
            switchGatewayDialog();
            break;
        // 编辑道闸/门禁
        case 'editRoadGate':
        case 'editAccessControl':
            state.gatewayForm.name = state.buildingTreeCurrentNodeData.name;
            state.gatewayForm.subType = state.buildingTreeCurrentNodeData.subType;
            switchGatewayDialog();
            break;
        // 管理点位
        case 'managePoint':
            switchPointDrawer();
            break;
        // 删除道闸/门禁
        case 'deleteGateway':
            deleteGateway();
            break;
        // 编辑点位
        case 'editPoint':
            switchEditPointDrawer();
            break;
    }
};

// 开关楼栋Dialog
const switchBuildingDialog = () => {
    state.buildingDialogShow = !state.buildingDialogShow;
    if (!state.buildingDialogShow) {
        currentInstance.refs['buildingFormRef'].resetFields();
    }
};
// 开关出入门Dialog
const switchGateDialog = () => {
    state.gateDialogShow = !state.gateDialogShow;
    if (!state.gateDialogShow) {
        currentInstance.refs['gateFormRef'].resetFields();
    }
};
// 开关门禁/道闸Dialog
const switchGatewayDialog = () => {
    state.gatewayDialogShow = !state.gatewayDialogShow;
    if (!state.gatewayDialogShow) {
        currentInstance.refs['gatewayFormRef'].resetFields();
        return;
    }
    state.gatewayFormRules = {
        name: [
            { required: true, message: +state.buildingTreeCurrentNodeData.gateType === 5 ? '请输入门禁名称' : '请输入道闸名称', trigger: 'blur' },
        ],
        subType: [
            { required: true, message: +state.buildingTreeCurrentNodeData.gateType === 5 ? '请选择门禁类型' : '请选择道闸类型', trigger: 'change' },
        ],
    };
};
// 开关管理点位Drawer
const switchPointDrawer = () => {
    state.pointDrawerShow = !state.pointDrawerShow;
    console.log(state.buildingTreeCurrentNodeData)
};
// 开关编辑点位Drawer
const switchEditPointDrawer = () => {
    state.editPointDrawerShow = !state.editPointDrawerShow;
};

// 新建楼栋
const addBuilding = () => {
    currentInstance.refs['buildingFormRef'].validate(async (valid:Boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                let params = {
                    premisesId: state.buildingTreeCurrentNodeData.id,
                    ...state.buildingForm,
                }
                await resourceApi.addBuilding(params);
                currentInstance?.appContext.config.globalProperties.$message.success('新建成功');
                switchBuildingDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 修改楼栋名称
const updateBuildingName = async () => {
    currentInstance.refs['buildingFormRef'].validate(async (valid:Boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                let params = {
                    buildId: state.buildingTreeCurrentNodeData.id,
                    ...state.buildingForm,
                }
                await resourceApi.updateBuildingName(params);
                currentInstance?.appContext.config.globalProperties.$message.success('编辑成功');
                switchBuildingDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 删除楼栋
const deleteBuilding = async () => {
    try {
        let params = {
            buildId: state.buildingTreeCurrentNodeData.id,
        }
        await resourceApi.deleteBuilding(params);
        currentInstance?.appContext.config.globalProperties.$message.success('删除成功');
        emit('onDataChange');
    } finally {}
};

// 新建出入门
const addGate = () => {
    currentInstance.refs['gateFormRef'].validate(async (valid:Boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                let params = {
                    premisesId: state.buildingTreeCurrentNodeData.id,
                    ...state.gateForm,
                }
                await resourceApi.addGate(params);
                currentInstance?.appContext.config.globalProperties.$message.success('新建成功');
                switchGateDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 修改出入门名称
const updateGateName = async () => {
    currentInstance.refs['gateFormRef'].validate(async (valid:Boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                let params = {
                    gateId: state.buildingTreeCurrentNodeData.id,
                    ...state.gateForm,
                }
                await resourceApi.updateGateName(params);
                currentInstance?.appContext.config.globalProperties.$message.success('编辑成功');
                switchGateDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 删除出入门
const deleteGate = async () => {
    try {
        let params = {
            gateId: state.buildingTreeCurrentNodeData.id,
        }
        await resourceApi.deleteGate(params);
        currentInstance?.appContext.config.globalProperties.$message.success('删除成功');
        emit('onDataChange');
    } finally {}
};

// 新建道闸/门禁
const addGateway = () => {
    currentInstance.refs['gatewayFormRef'].validate(async (valid:Boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                let params = {
                    premisesId: state.buildingTreeCurrentNodeData.premisesId,
                    gateId: state.buildingTreeCurrentNodeData.id,
                    gateType: state.currentOperateMenuItem.command === 'addAccessControl' ? 5 : 6, // gateType-门体类型：5.门禁，6.道闸
                    ...state.gatewayForm,
                }
                await resourceApi.addGateway(params);
                currentInstance?.appContext.config.globalProperties.$message.success('新建成功');
                switchGatewayDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 修改道闸/门禁
const updateGateway = async () => {
    currentInstance.refs['gatewayFormRef'].validate(async (valid:Boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                let params = {
                    gatewayId: state.buildingTreeCurrentNodeData.id,
                    ...state.gatewayForm,
                }
                await resourceApi.updateGateway(params);
                currentInstance?.appContext.config.globalProperties.$message.success('编辑成功');
                switchGatewayDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 删除道闸/门禁
const deleteGateway = async () => {
    try {
        let params = {
            gatewayId: state.buildingTreeCurrentNodeData.id,
        }
        await resourceApi.deleteGateway(params);
        currentInstance?.appContext.config.globalProperties.$message.success('删除成功');
        emit('onDataChange');
    } finally {}
};
</script>

<style lang="scss" scoped>
.building-tree-access-door {
    height: 100%;
}
</style>
